package cn.tedu.charging.order.utils;

import cn.tedu.charging.common.constant.XxlJobAuthConst;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class XxlJobTaskUtil {
    public static boolean createJobTask(RestTemplate restTemplate, String cronExpression, Integer jobGroup, String orderNo,Integer userId){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.set("Cookie", XxlJobAuthConst.COOKIE_NAME_VALUE);
        MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
        formData.add("jobGroup", "4"); // TODO 注意:XXL-JOB需要字符串形式的数字,此处需在xxl_job数据库的xxl_job_group表中id字段中获得
        formData.add("jobDesc", "充电桩定时自检");
        formData.add("author", "admin");
        formData.add("alarmEmail", "");
        formData.add("scheduleType", "CRON");
        formData.add("scheduleConf", cronExpression);
        formData.add("executorBlockStrategy", "SERIAL_EXECUTION");
        formData.add("misfireStrategy", "DO_NOTHING");
        formData.add("executorRouteStrategy", "FIRST");
        formData.add("executorHandler", "checkSuccessStatus");//@XxlJob
        String timerParam="{\"orderNo\":\""+orderNo+"\",\"userId\":\""+userId+"\"}";
        formData.add("executorParam", timerParam);
        formData.add("executorTimeout", "0");
        formData.add("executorFailRetryCount", "0");
        formData.add("glueType", "BEAN");
        formData.add("glueSource", "");
        formData.add("glueRemark", "GLUE代码初始化");
        formData.add("childJobId", "");
        formData.add("triggerStatus", "1");
        formData.add("triggerLastTime", "0");
        formData.add("triggerNextTime", "0");

        String adminUrl = "http://localhost:8080/xxl-job-admin/jobinfo/add";
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(formData, headers);
        ResponseEntity<String> response = restTemplate.exchange(
                adminUrl,
                HttpMethod.POST,
                request,
                String.class
        );
        // 4. 验证响应
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("延迟任务设置成功，将在1分钟后执行");
            return true;
        } else {
            System.out.println("设置失败: " + response.getBody());
            return false;
        }
    }
}
